package mud.controller;

import mud.entity.User;
import mud.repository.UserRepository;
import mud.support.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("")
    public Map<String, String> index() {
        Map<String, String> map = new HashMap<>();
        map.put("date", DateUtil.getDateString());
        map.put("status", "Running");
        return map;
    }

    @GetMapping("/add")
    public User addUser(
            @RequestParam("name") String name,
            @RequestParam("age") Integer age,
            @RequestParam(value = "address",
                    defaultValue = "local", required = false) String address
    ) {
        User user = new User(name, age, address);
        return userRepository.save(user);
    }

    @GetMapping("/name/{name}")
    public User findUser(@PathVariable("name") String name) {
        User user = userRepository.findByName(name);
        if (user == null) {
            user = new User("None", "None", 0, "None");
        }
        return user;
    }

    @GetMapping("/find/{name}")
    public List<User> findUsers(@PathVariable("name") String name) {
        return userRepository.findByNameContaining(name);
    }

    @GetMapping("/update")
    public User updateUser(
            @RequestParam("name") String name,
            @RequestParam("age") Integer age,
            @RequestParam(value = "address",
                    defaultValue = "local", required = false) String address
    ) {
        User user = userRepository.findByName(name);
        if (user == null) {
            user = new User("None", "None", 0, "None");
            return user;
        } else {
            if (user.getAge().equals(age) && user.getAddress().equals(address))
                return user;

            user.setAge(age);
            user.setAddress(address);
            return userRepository.save(user);
        }
    }
}
